import { Injectable } from '@angular/core';
import {
  HttpEvent, HttpInterceptor, HttpHandler, HttpRequest
} from '@angular/common/http';
import { NbAuthSimpleToken, NbTokenService } from '@nebular/auth';
import { Observable } from 'rxjs';
import { switchMap, take } from 'rxjs/operators';

@Injectable()
export class TokenInterceptor implements HttpInterceptor {

  constructor(
    private _tokenService: NbTokenService,
  ) {}

  intercept(req: HttpRequest<any>, next: HttpHandler):
    Observable<HttpEvent<any>> {

      const auth = req.headers.get('authorization');
      return this._tokenService.get().pipe(
        take(1),
        switchMap((token: NbAuthSimpleToken) => {
          if (!auth) {
            req = req.clone({
              setHeaders: {
                'Authorization': `Bearer ${token.getValue()}`,
              }
            });
          }
          return next.handle(req);
        })
      );
  }
}
